package com.example.text6_client;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

class ClientThread extends Thread {
    private final static int WHAT = 0x1234;
    private final static int REMOTE_PORT = 5000;

    private DatagramSocket remoteDs;
    private InetAddress remoteAddress;

    private final byte[] buf = new byte[1024];

    private static Handler sendHandler;

    public ClientThread() {
        try {
            remoteDs = new DatagramSocket();
            remoteAddress = InetAddress.getByName("127.0.0.1");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(String str) {
        sendHandler.obtainMessage(WHAT, str).sendToTarget();
    }

    public void onDestroy() {
        if (remoteDs != null) {
            remoteDs.close();
        }
    }

    @Override
    public void run() {
        Looper.prepare();
        sendHandler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == WHAT) {
                    byte[] buffer = ((String) msg.obj).getBytes();
                    DatagramPacket remoteDp = new DatagramPacket(buffer, buffer.length, remoteAddress, REMOTE_PORT);
                    try {
                        remoteDs.send(remoteDp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Looper.loop();
    }
}